package com.yida.service;

import com.yida.bean.*;
import com.yida.dao.Mapper;
import com.yida.util.emailHtml;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.mail.internet.MimeMessage;
import javax.servlet.http.HttpSession;
import java.sql.Date;
import java.util.*;


@Service
public class serverblogImpl implements serverblog{

	@Autowired
	public  Mapper mapper;

	@Autowired
	JavaMailSender MailSender;

	@Override
	public List<blog> selectblog(Integer page) {
		// TODO Auto-generated method stub
		Integer pagetail= 10 ;
		Integer pagehead = (page-1)*pagetail;
		
	    List<blog> blogList = mapper.selectBlogall(pagehead,pagetail);
		return	blogList;
	}

	public Integer selectBlogsSumservice() {
		Integer sum = mapper.selectBlogsSum().size();
		// TODO Auto-generated method stub
		if (sum%10==0) {
			return  (sum/10);
		}else {
		    return  (sum/10)+1;
	}
		
	}

	@Override
	public blogger selectBloggerindexservice() {
		// TODO Auto-generated method stub
		return	mapper.selectBloggerindex();
	
	}
//前五条热门
	@Override
	public List<blog> selectblogreservice() {
		// TODO Auto-generated method stub
		return mapper.selectBlogre();
	}
	
//查询博客详情
	@Override
	public blog selectBlogservice(Integer id) {
		// TODO Auto-generated method stub
		blog  blog =  mapper.selectBlog(id);
		//System.out.println( MarkdownUtils.markdownToHtmlExtensions( "[fereli 爱编程](http://www.lirenmi.cn)")); 
		return blog;
	}

	@Override
	public List<blogtype> selectblogtypeservice() {
		// TODO Auto-generated method stub
		return mapper.selectblogtype();
	}

	//3d图所需数据
	@Override
	public int[] selectdateallservice() {
		
		List<Date> date = mapper.selectdateall();
		Map<String, Integer> map = new HashMap<String, Integer>();
		 int[] zu= new int[12];
		
		   for(int i=0;i<date.size();i++) {
		       Integer month = date.get(i).getMonth();
			      zu[month] = zu[month] + 1;
		   }
		   System.out.println(zu.length);
		// TODO Auto-generated method stub
		return zu;
	}

	
	//日志
	@Override
	public List<log> selectlogservice(Integer page) {
		Integer pagetail=4 ;
		Integer pagehead = (page-1)*pagetail;
	    List<log> logList = mapper.selectlog(pagehead,pagetail);
		
		// TODO Auto-generated method stub
		return logList;
	}
	
	//按id、查询分类博文
	public List<blog> selectBlogtotype(Integer page, Integer id) {
		// TODO Auto-generated method stub
		Integer pagetail= 7 ;
		Integer pagehead = (page-1)*pagetail;
		return mapper.selectBlogtotype(pagehead, pagetail, id);
		
	}
   //类型下的博客数量
		@Override
		public List<Integer> selecttypeBlogsSumservice(Integer id) {	
			// TODO Auto-generated method stub
			return mapper.selecttypeBlogsSum(id);
		}
	
	
	

	
	
	
	
	//验证博主登录
	@Override
	public blogger selectBloggerservice(String username, String password) {
		// TODO Auto-generated method stub
		return mapper.selectBlogger(username, password);
	}
	
	//查询分类
	@Override
	public List<blogtype> selectBlogtypesservice(Integer page) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
				Integer pagetail= 10 ;
				Integer pagehead = (page-1)*pagetail;
			    List<blogtype> blogtype = mapper.selectBlogtypes(pagehead, pagetail);
		return blogtype;
	}
	
	//分类数量
	@Override
	public Integer selectTypeSumservice() {
		// TODO Auto-generated method stub
		return   ((mapper.selectTypeSum().size())/10)+1;
	}
	
	//查询标签
	@Override
	public List<tag> selecttagservice() {
		// TODO Auto-generated method stub
		return mapper.selecttag();
	}
	
	//查询标签下的博客
	@Override
	public List<blog> selecttagBlogservice(Integer page, Integer id) {
		// TODO Auto-generated method stub
		Integer pagetail= 10 ;
		Integer pagehead = (page-1)*pagetail;

		return 	mapper.selecttagBlog(pagehead, pagetail, id);
	}

   //查询标签下的博客页数
	@Override
	public Integer selecttagBlogsumservice(Integer id) {
		
		Integer sum = mapper.selecttagBlogsum(id).size();
		if (sum%10==0) {
			return sum/10;
		}else {
			return sum/10+1;
		}
		
	}
	
	//查询关键字
	@Override
	public List<blog> searchservice(String keyword) {
		// TODO Auto-generated method stub
		return mapper.search(keyword);
	}
	
	 
	//查询评论
	@Override
	public List<comment> listCommentByBlogId(Integer blogId) {
		// TODO Auto-generated method stub
         List<comment> comments =	mapper.selectcomment(blogId);
		return 	eachComment(comments);
	}
	
	//查询留言评论
	@Override
	public List<comment> leavecomment() {
		// TODO Auto-generated method stub
	   List<comment> comments =	mapper.selectleavecomment();
	   return eachComment(comments);
	}

	
	

    /**
     * 循环每个顶级的评论节点
     * @param comments
     * @return
     */
    private List<comment> eachComment(List<comment> comments) {
        List<comment> commentsView = new ArrayList<>();
        for (comment comment : comments) {
            comment c = new comment();
            BeanUtils.copyProperties(comment,c);
            commentsView.add(c);
        }
        //合并评论的各层子代到第一级子代集合中
        combineChildren(commentsView);
        return commentsView;
    }

    /**
     *
     * @param comments root根节点，blog不为空的对象集合
     * @return
     */
    private void combineChildren(List<comment> comments) {
        for (comment comment : comments) {
            List<comment> replys1 = comment.getReplycommenet();
            for(comment reply1 : replys1) {
                //循环迭代，找出子代，存放在tempReplys中
                recursively(reply1);
            }
            //修改顶级节点的reply集合为迭代处理后的集合
            comment.setReplycommenet(tempReplys);
            //清除临时存放区
            tempReplys = new ArrayList<>();
        }
    }

    //存放迭代找出的所有子代的集合
    private List<comment> tempReplys = new ArrayList<>();
    /**
     * 递归迭代，剥洋葱
     * @param comment 被迭代的对象
     * @return
     */
    private void recursively(comment comment) {
        tempReplys.add(comment);//顶节点添加到临时存放集合
        if (comment.getReplycommenet().size()>0) {
            List<comment> replys = comment.getReplycommenet();
            for (comment reply : replys) {
                if (reply.getReplycommenet().size()>0) {
                    recursively(reply);
                }else {
					tempReplys.add(reply);
				}
            }
        }
    }
	
	
	
	
	
	
	
	
	
	
	

	
	

	//新增评论
	@Override
	public Integer saveConmment(comment comment,HttpSession session,Integer pd,Integer blogxqid,String email) {
		// TODO Auto-generated method stub
		//随机图片的地址
		String[] img = {
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2014278.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2035567.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2046017.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2052796.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2053919.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2053942.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054350.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054480.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054618.jpg",
				"https://bloggerdisk.oss-cn-hangzhou.aliyuncs.com/image/email/2054956.jpg"
		 };



		//后台博主信息
			    blogger blogger = (blogger) session.getAttribute("blogger");
			    
		    //    String imgurl = "/static/img/nm.png";
		//用户信息
			      blogUser user2 = (blogUser) session.getAttribute("user");
			     
			      String imgurl = user2.getImgUrl();
		      /*  if (seal) {
		        	imgurl = "https://q4.qlogo.cn/g?b=qq&nk="+qq+"&s=100";
				}
			  */

		//默认游客
		comment.setAdminComment(0);

		//判断是否是友人
		  if( mapper.judgeemail(email)!=null ){
			  comment.setAdminComment(2);   //状态2表示友人
		 }

                if (blogger!=null) {
                	imgurl = blogger.getImageurl();
                	comment.setAdminComment(1);
                	comment.setNickname(blogger.getNickName());
				}
		        comment.setImgurl(imgurl);


		        //验证昵称
		        if (comment.getNickname()==null) {
					comment.setNickname("匿名用户");
				}

		        if(pd==1) {

						try {
							//创建邮件消息
							MimeMessage message = MailSender.createMimeMessage();
							MimeMessageHelper helper = new MimeMessageHelper(message, true);
							//谁发的
							helper.setFrom("1320123744@qq.com");
							//根据id查询用户信息

							//给博主发邮箱
							if (comment.getReplyid() == null) {
//谁要接收
								helper.setTo("1320123744@qq.com");
//邮件标题
								helper.setSubject("来自Smile的邮件");

								String html = emailHtml.buildBloggerHtml(
										img[new Random().nextInt(10)],  //随机图片
										"博主益达",
										comment.getNickname(),
										comment.getContent(),
										blogxqid.toString()
								);
								//设置内容
								helper.setText(html, true);
								//发送邮件
								MailSender.send(message);

							} else {
								//给用户发邮箱
								//找出评论父用户信息
								blogUser commentfather = mapper.replyIdByBlogUser(comment.getReplyid());
						//如果父用户的邮箱不为空的情况下才发邮件

								if (commentfather.getEmail() != null) {

									//谁要接收
									helper.setTo(commentfather.getEmail());
									//邮件标题
									helper.setSubject("来自Smile的邮件");
									//填充数据
									//查询父评论内容
									String fathercontent = mapper.selectcontent(comment.getReplyid());
									//邮件内容


									String html = emailHtml.buildUserHtml(
											img[new Random().nextInt(10)],  //随机图片
											commentfather.getNickname(),
											fathercontent,
											comment.getNickname(),
											comment.getContent(),
											blogxqid.toString()
									);

									helper.setText(html, true);
									MailSender.send(message);
								}
							}
						} catch (Exception e) {
							e.printStackTrace();
							return 0;
						}

		        	return mapper.insertcomment(comment);

					//如果是留言
		        }else{



				try {
					//创建邮件消息
					MimeMessage message = MailSender.createMimeMessage();
					MimeMessageHelper helper = new MimeMessageHelper(message, true);
					//谁发的
					helper.setFrom("1320123744@qq.com");
					//根据id查询用户信息

					//给博主发邮箱
					if (comment.getReplyid() == null) {
//谁要接收
						helper.setTo("1320123744@qq.com");
//邮件标题
						helper.setSubject("来自Smile的邮件");

						String html = emailHtml.buildBloggerHtmlComment(
								img[new Random().nextInt(10)],  //随机图片
								"博主益达",
								comment.getNickname(),
								comment.getContent(),
								"https://taoyida.top/about"
						);
						//设置内容
						helper.setText(html, true);
						//发送邮件
						MailSender.send(message);

					} else {
							//给用户发邮箱
							//找出评论父用户信息
							blogUser commentfather = mapper.replyIdByBlogUser(comment.getReplyid());
					//如果父用户的邮箱不为空的情况下

					if (commentfather.getEmail() != null) {
							//谁要接收
							helper.setTo(commentfather.getEmail());
							//邮件标题
							helper.setSubject("来自Smile的邮件");
							//填充数据
							//查询父评论内容
							String fathercontent = mapper.selectcontent(comment.getReplyid());
							//邮件内容

							String html = emailHtml.buildUserHtmlComment(
									img[new Random().nextInt(10)],  //随机图片
									commentfather.getNickname(),
									fathercontent,
									comment.getNickname(),
									comment.getContent(),
									"https://taoyida.top/about"
							);

							helper.setText(html, true);
							MailSender.send(message);
						}

					}
				} catch (Exception e) {
					e.printStackTrace();
					return 0;
				}



		        	return mapper.insertleavecomment(comment);
				}
			
	}
	
	
	
	
	
	
   //增加阅读次数
	@Override
	@Transactional
	public Integer updateblogsumservice(Integer id) {
		// TODO Auto-generated method stub
		return mapper.updateblogsum(id); 
	}

	@Transactional
	@Override
	public Integer deletetypeservice(Integer id) {
		// TODO Auto-generated method stub
		return mapper.deletetype(id);
	}
	
	@Transactional
	@Override
	public Integer updatetypeservice(blogtype type) {
		// TODO Auto-generated method stub	
		return 	mapper.updatetype(type);
	}
 
	@Transactional
	@Override
	public Integer inserttypeservice(blogtype type) {
		// TODO Auto-generated method stub
		return mapper.inserttype(type);
	}

	
	//后端管理博客页面
	@Override
	public List<blog> selectBlogadmin(Integer page, blog blog,Integer type) {
		// TODO Auto-generated method stub
		Integer pagetail= 10 ;
		Integer pagehead = (page-1)*pagetail;
		return mapper.selectBlogadmin(pagehead,pagetail,blog,type);
	}
	//后端管理博客总页面
	@Override
	public Integer selectBlogsumadmin(blog blog, Integer type) {
		// TODO Auto-generated method stu
		int pagetail= 10 ;
		Integer sum = mapper.selectBlogsumadmin(blog, type).size();
		
		if (sum%pagetail==0) {
			return sum/pagetail;
		}else {
			return sum/pagetail+1;
		}
		
	}

	//插入博客
	@Transactional
	public boolean insertblog(blog blog, Integer type, int[] tagIds) {
		// TODO Auto-generated method stub
	
		int insertblog = mapper.insertblog(blog, type);
		
			for (int i = 0; i < tagIds.length; i++) {
				mapper.inserttag(blog.getId(),tagIds[i]);
			}
	
			if (insertblog>0) {
				return true;
			}else {
				return false;
			}
		
	}

	//删除博客
	@Transactional
	@Override
	public boolean delectblog(Integer id) {
		// TODO Auto-generated method stub
		Integer delectblog =  mapper.delectblog(id);
		Integer delecttag  =  mapper.delectblogtag(id);
		if (delectblog==1 && delecttag>0) {
			return true;
		}else {
			return false;
		}
		
	}

	//修改博客
	@Override
	@Transactional
	public boolean updateblog(blog blog, Integer type, int[] tagIds) {
		// TODO Auto-generated method stub
		// TODO Auto-generated method stub
		Integer updateblog =  mapper.updateblog(blog, type);
		Integer delecttag  =  mapper.delectblogtag(blog.getId());
		 for (int i = 0; i < tagIds.length; i++) {
			mapper.inserttag(blog.getId(),tagIds[i]);
		 }
		  if (updateblog==1 && delecttag==1) {
					return true;
				}else {
					return false;
				}
	}






}
